package com.example.ecs.core;

import java.util.ArrayList;
import java.util.List;

/**
 * EntityManager类负责管理所有的实体和系统
 */
public class EntityManager {
    private List<Entity> entities;
    private List<System> systems;
    private boolean initialized = false;
    
    public EntityManager() {
        this.entities = new ArrayList<>();
        this.systems = new ArrayList<>();
    }
    
    public Entity createEntity() {
        Entity entity = new Entity();
        entities.add(entity);
        
        // 如果系统已经初始化，则将实体添加到所有系统中
        if (initialized) {
            for (System system : systems) {
                system.addEntity(entity);
            }
        }
        
        return entity;
    }
    
    public void removeEntity(Entity entity) {
        entities.remove(entity);
        // 从所有系统中移除该实体
        for (System system : systems) {
            system.removeEntity(entity);
        }
    }
    
    public void addSystem(System system) {
        systems.add(system);
        // 如果实体已经存在，则将现有实体添加到新系统中
        if (initialized) {
            for (Entity entity : entities) {
                system.addEntity(entity);
            }
        }
    }
    
    public void removeSystem(System system) {
        systems.remove(system);
    }
    
    public void initialize() {
        // 初始化所有系统，将现有实体添加到系统中
        for (System system : systems) {
            for (Entity entity : entities) {
                system.addEntity(entity);
            }
        }
        initialized = true;
    }
    
    public void update(double deltaTime) {
        // 更新所有系统
        for (System system : systems) {
            system.update(deltaTime);
        }
    }
    
    public List<Entity> getEntities() {
        return entities;
    }
    
    public List<System> getSystems() {
        return systems;
    }
}